import classNames from 'classnames'
import { AtTabs, AtTabsPane } from 'taro-ui'
import Taro, { Component, showLoading } from '@tarojs/taro'
import { View, Text } from '@tarojs/components'
import { DNavBar, DImagesupload, DSelectColor, DAtInpute, DSelectMap, DButtonModal, Ddialog } from '@/components'
import { AtForm, AtButton, AtSwitch, AtActionSheet } from 'taro-ui'
import Cardealer from './cardealer'
import http from '@/api'
import common from '@/common'
import sdk from '@/common/sdk'
import '../carform/carform.scss'
import './applyform.scss'
const statusMortgage = common.statusMortgage
const belongToBankList = common.belongbankList
export default class CarformBox extends Component {

  constructor(props) {
    super(props)
    this.state = {
      title: '按揭登记',
      isOpenedColor: false,
      showAuthTip: false,
      status: '2',
      id: false,
      current: 0,
      listColr: [],
      seletOne: {
        defNoop: () => {
          this.state.seletOne.isOpened = false
          this.setState({
            seletOne: { ...this.state.seletOne },
          })
        }
      }, // 单选对象
      carform: {
        cusName: '',
        cusMobile: '',
        //carDataModel:'',
        carModelName: '',
        outColor: '',
        guidePrice: '',
        loanPrice: '',
        loanRate: '',
        loanDate: '',
        // status:0,
        signBank: '',
        registrationCity: '',
        entName: '',
        servicerName: '',
        orgName: ''
      },
      // 颜色key值
      // belongToBankList:require('@/common/').default.belongbankList,
      colorKey: "",
      selectColor: "",
      colorCount: 2,
      type: "",
      disabled: true,
      tips1: '请选择车辆类型'
    }
  }

  componentWillMount() {
    let { status = '2', id = '', type = '', editId } = this.$router.params
    this.checkPermission();
    let { title } = this.state
    editId && this.getDetail(editId);
    if (id) {
      this.getRegistration(id)
    }
    sessionStorage.removeItem('brandList')
    this.setState({
      status,
      type,
      id: !!id
    })
  }

  componentDidShow() {
    this.getBrandInfo()
    sdk.setTitleInfo(this.state.title)

  }

  // 权限校验
  async checkPermission() {
    const { eaIsAppro } = await http.getConfirmInfo()
    const { imIdStatus } = await http.myselfDetail()
    if (eaIsAppro != 1 && imIdStatus != 2) {
        this.setState({
            showAuthTip: true
        })
    } else {
        this.getServicer()
    }
  }

  getServicer() {
    http.getServicer().then(res => {
      let carform = this.state.carform
      carform.orgId = res.orgId
      carform.entId = res.entId
      carform.entName = res.entName
      carform.orgName = res.orgName
      carform.servicerId = res.servicerId
      carform.servicerName = res.servicerName
      this.setState({
        carform
      })
    })
  }
  getFilterPlace(first, second) {
    let _itemPlace = ['北京市', '天津市', '上海市', '重庆市']
    _itemPlace.map(item => {
      if (item === first) {
        second = item
      }
    })
    return second
  }


  getBrandInfo() {
    let _brandList = sessionStorage.getItem('brandList')

    if (!_brandList) {
      return
    }
    let { carBrand = '',
      carBrandId = '',
      carBrandLogo = '',
      carModel = '',
      carSourceType = '',
      carGuiPrice = 0,
      carModelId = '',
      carSeries = '',
      carSeriesId = '',
      waiguanyanse = ''
    } = JSON.parse(_brandList)
    // carGuiPrice = Number(carGuiPrice/10000).toFixed(2)

    let _obj = {
      // carDataBrand: carBrand,
      // carDataBrandId: carBrandId,
      //carDataBrandLogo: carBrandLogo,
      //carDataModel: carModel,
      // carSourceType: carSourceType,
      guidePrice: carGuiPrice,
      carModelId: carModelId,
      carModelName: carModel,
      // outColor: arrColr.join('/'),//外观颜色
      //neishiyanse, //neishiyanse
      //carDataSeries: carSeries,
      //carDataSeriesId: carSeriesId
    }
    let { carform } = this.state
    carform = Object.assign(carform, _obj)
    this.setState({
      carform,
      waiguanyanse,
      listColr: require('@/common/').default.getSplitColor(waiguanyanse)
    }, () => {
      sessionStorage.removeItem('brandList')
    })
  }
  getDetail(id) {
    http.getRegistration(id).then(res => {
      this.setState({
        carform: { ...res }
      })
    })
  }
  // 获取详情
  getRegistration(id) {
    let { status } = this.$router.params

    let _http
    if (+status === 2) {
      // 车商 - 按揭 详情
      _http = http.getRegistration(id)
    } else {
      // 按揭详情
      _http = http.getRegistration(id)
    }
    let { carform } = this.state
    _http.then(res => {
      carform = Object.assign({}, res)
      carform.carRemark = ''
      this.setState({
        carform,
      })

    })
  }

  onSubmitHandle() {
    let { carform, status, title, disabled, tips1 } = this.state

    function urlInfo(status) {
      return {
        $1: '/pages/index/index',
        $2: '/pages/usercar/usercar'
      }[`$${status}`]
    }
    // if (disabled) {
    //   return Taro.showToast({
    //     icon: "none",
    //     title: tips1
    //   })
    // }
    const isPhone = require('@/common/').default.iphoneTest
    if (!isPhone(this.state.carform.cusMobile)) {
      return Taro.showToast({
        icon: "none",
        title: '请输入正确的号码!'
      })
    }
    // if ((0.5 * Number(carform['carGuiPrice'])) > Number(carform['carOfferPrice']) || Number(carform['carOfferPrice']) > (2 * Number(carform['carGuiPrice']))) {
    //   return Taro.showToast({
    //     title: `请输入${status === '2' ? '车辆报价' : '期望报价'}是车辆指导价的0.5或者2倍之间`,
    //     icon: 'none'
    //   })
    // }

    let car = carform

    let httpApi = this.$router.params.editId ? http.replaceSaveReload : http.saveRegistration

    httpApi(car)
      .then(res => {
        Taro.showToast({
          title: '已提交登记按揭',
          duration: 800,
          mask: true
        }).then(() => {
          setTimeout(() => {
            Taro.redirectTo({
              url: '/pages/mortgage/mortgage'
            })
          }, 1000)
        })
      })
      .catch(() => {
        Taro.showToast({
          title: "网络异常！",
          icon: "none"
        })
      })
  }

  onRightHanlde(key) {
    if (this.state.id) return;
    let { waiguanyanse, neigaunyanse } = this.state
    let isOut = key === 'outColor'
    this.setState({
      isOpenedColor: true,
      colorKey: key,
      listColr: common.getSplitColor(isOut ? waiguanyanse : neigaunyanse),
      colorCount: key === 'outColor' ? 0 : 2,
      selectColor: this.state.carform[key]
    })
  }

  onCancelHandle() {
    this.setState({
      isOpenedColor: false
    })
  }

  onSubmitColor(value) {
    let { colorKey } = this.state
    let color = []
    value.map(item => {
      color.push(item.color)
    })
    this.bindCarform(colorKey, color.join('/'))
    this.setState({
      isOpenedColor: false
    })
  }

  onHandleSelect() {
    if (this.state.id) return;
    Taro.navigateTo({
      url: "/pages/choosebrand/choosebrand"
    })
  }

  initSelectOne = ({ title, bind }, sList) => {
    return new Promise((res, rej) => {
      this.setState({
        seletOne: {
          ...this.state.seletOne,
          isOpened: true,
          title,
          sList: sList.filter(item => (item.status = this.state.carform[bind] === item.text, true)), // 反显高亮值
          selectListItem: (item) => {
            item.status = !item.status
            if (item.status) {
              this.state.seletOne.value = item
              res.call(this, item)
            }
            this.state.seletOne.isOpened = false
            this.setState({
              seletOne: { ...this.state.seletOne },
            })
          }
        }
      })
    })
  }

  bindCarform = (key, value) => {
    if (key) {
      if (key === 'carOfferPrice') {
        let Digit = common.getDigit(value, this.state.carform.carOfferPrice)
        // debugger
        this.setState({
          carform: Object.assign(this.state.carform, { [key]: Digit }),
        }, () => {
          this.getCarStatus()
        })
      } else {
        this.setState({
          carform: Object.assign(this.state.carform, { [key]: value }),
        }, () => {
          this.getCarStatus()
        })
      }
    }

  }

  getCarStatus() {
    let { carform, status } = this.state
    let _statusForm = false, _item = ''

    let _carformfirst = ['cusName', 'cusMobile', 'outColor',
      'guidePrice', 'loanPrice', 'loanRate', 'loanDate', 'signBank', 'registrationCity']

    let objtext = {
      cusName: '请输入客户名称',
      cusMobile: '请输入电话号码',
      outColor: '请选择外观颜色',
      guidePrice: '请输入指导价',
      loanPrice: '请输入贷款金额',
      loanRate: '请输入利率',
      loanDate: '请输入贷款期限',
      signBank: '请选择签件银行',
      registrationCity: '请选择上牌地点',
    }
    for (let i = 0, j = _carformfirst.length; i < j; i++) {
      if (!carform[_carformfirst[i]]) {
        _statusForm = true
        _item = objtext[_carformfirst[i]]
        break
      }
    }
    // _carformfirst.map(item => {
    //   if (!carform[item]) {
    //     _statusForm = true
    //   }
    // })



    this.setState({
      disabled: _statusForm,
      tips1: _item
    })
  }

  selectCarPop = (props) => {
    this.initSelectOne(props, [
      { text: '国五' },
      { text: '国六' },
      { text: '纯电动' }
    ]).then(selectItem => {
      this.bindCarform(props.bind, selectItem.text)
    })
  }
  selectloadDate = (props) => {
    if (this.state.id) return;

    this.initSelectOne(props, [
      { text: '12期' },
      { text: '24期' },
      { text: '36期' },
      { text: '48期' },
      { text: '60期' }
    ]).then(selectItem => {
      this.bindCarform(props.bind, `${selectItem.text}`)
    })
  }
  selectCarDate = (props) => {
    if (this.state.id) return;
    let a = []
    belongToBankList.map(list => {
      a.push({ text: list })
    })
    this.initSelectOne(props, a).then(selectItem => {
      this.bindCarform(props.bind, selectItem.text)
    })
  }

  selectHandInfo = (props) => {
    this.initSelectOne(props, [
      { text: '手续齐全' },
      { text: '手续办理中' }
    ]).then(selectItem => {
      this.bindCarform(props.bind, selectItem.text)
    })
  }

  selectCarSource = (props) => {
    this.initSelectOne(props, [
      { text: '自店' },
      { text: '资源' }
    ]).then(selectItem => {
      this.bindCarform(props.bind, selectItem.text)
    })
  }

  selectCarGoodDate = props => {
    this.initSelectOne(props, [
      { text: '现货' },
      { text: '期货' }
    ]).then(selectItem => {
      this.bindCarform(props.bind, selectItem.text)
    })
  }

  selectCarStatus = props => {
    this.initSelectOne(props, [
      { text: '客户寻车，寻求报价' },
      { text: '订金在手，价好即接' }
    ]).then(selectItem => {
      this.bindCarform(props.bind, selectItem.text)
    })
  }
  handleClick(value) {
    // let item = value === 1 ? this.state.item2 : this.state.item3
    this.setState({
      current: value,
      // item
    })
  }

  onCancel() {
    this.setState({
        showAuthTip: false,
    })
}
    onSure() {
        Taro.redirectTo({
            url: `/pages/myinfo/authentication`
        })
    }

  render() {
    const {
      title,
      isOpenedColor,
      carform,
      seletOne,
      selectColor,
      colorCount,
      id,
      current,
      showAuthTip
    } = this.state
    const { status } = this.$router.params
    const place = carform.status
    const _bindCarform = function (value) {
      this.bindCarform(arguments[arguments.length - 1].bind, value)
    }
    const _swichBindCarform = function (key, value) {
      this.bindCarform(key, +value)
    }
    const _selectMap = function (key, value) {
      let { first = '', secode = '' } = value
      let region = first + secode
      // if (status === '1') {
      //   this.bindCarform("carTransAddr", this.getFilterPlace(first, secode))
      //   this.bindCarform('carTransAddrDetail', first === this.getFilterPlace(first, secode) ? first : region)
      //   this.bindCarform('carTransDis', first)
      // }
      this.bindCarform(key, region)
    }
    const _imageList = function (key, value) {
      let _value = []
      value.map(item => {
        if (item.url) {
          _value.push({
            id: item.id,
            type: item.uploadType,
            cfUrl: item.url
          })
        }
      })
      this.bindCarform(key, _value)

    }
    return (
      <View className={'b_carform b_mortgage ' + (id ? 'isEdit' : '')}>
        <DNavBar title={title}></DNavBar>
        {
          id && +carform.status == 1 && (<View className={'tabsBox'}><AtTabs current={current}
          scroll
          tabList={[
            { title: '详情' },
            { title: '推荐' },
          ]}
          className='b_companydetail_tabs-navigation__header'
          onClick={this.handleClick.bind(this)}></AtTabs></View>)
        }
        {(current === 0 || !id) && <View className='b_carform__box'>
          <View className='b_carform__form' >
            <AtForm>
              {id && <View className={'statusMortgage'}>
                { /*+(+place>0?'close':'check')+'-circle'*/
                  +place >= 0 && <View className={'b_carinfo__name_place at-icon at-icon-' + (+place > 0 ? +place === 1 ? 'check' : +place === 2 ? 'close' : +place === 3 ? 'arrow-left' : 'clock' : 'clock')}>{statusMortgage[+carform.status]}</View>
                }
              </View>}
              <View className='b_carform__form__item' style={'clear:both'}>
                <Text className='b_carform__form_title'>车辆信息</Text>
                <DAtInpute disabled={id} value={carform.cusName} bind='cusName' require={true} onChange={_bindCarform.bind(this)} title='客户姓名' placeholder={!id ? '请输入客户姓名' : ''}></DAtInpute>
                <DAtInpute disabled={id} value={carform.cusMobile} bind='cusMobile' require={true} onChange={_bindCarform.bind(this)} title='联系电话' type={!id ? 'number' : 'text'} placeholder={!id ? '请输入客户联系电话' : ''}></DAtInpute>
                <DAtInpute disabled={id} value={carform.carModelName} bind='carModelName' onChange={_bindCarform.bind(this)} title='车型' icon='chevron-right' require={true} placeholder={!id ? '请选择车型' : ''} onRightHanlde={this.onHandleSelect.bind(this)}></DAtInpute>
                <DAtInpute disabled={id} value={carform.outColor} bind='outColor' onChange={_bindCarform.bind(this)} title='外观颜色' require={true} icon='chevron-right' placeholder={!id ? '请选择车辆外观颜色' : ''} onRightHanlde={this.onRightHanlde.bind(this, 'outColor')}></DAtInpute>
                <DAtInpute disabled={id} value={carform.guidePrice} bind='guidePrice' type="number" onChange={_bindCarform.bind(this)} title='车辆指导价' placeholder={!id ? '车辆指导价' : ''}>万</DAtInpute>
              </View>
              {
                <View className='b_carform__form__item'>
                  <Text className='b_carform__form_title'>按揭信息</Text>
                  <DAtInpute disabled={id} value={carform.loanPrice || '--'} bind='loanPrice' require={true} onChange={_bindCarform.bind(this)} title='贷款金额' type='number' placeholder={!id ? '请输入贷款金额' : ''}>万</DAtInpute>
                  <DAtInpute disabled={id} value={carform.loanRate} bind='loanRate' require={true} onChange={_bindCarform.bind(this)} title='利率' placeholder={!id ? '请输入贷款利率' : ''}></DAtInpute>
                  <DAtInpute disabled={id} value={carform.loanDate} bind='loanDate' require={true} onChange={_bindCarform.bind(this)} title='贷款期限' placeholder={!id ? '请输入贷款期限' : ''} icon='chevron-right' onRightHanlde={this.selectloadDate} ></DAtInpute>
                  <DAtInpute disabled={id} value={carform.signBank} bind='signBank' require={true} onChange={_bindCarform.bind(this)} title='签件银行' icon='chevron-right' placeholder={!id ? '请选择签件银行' : ''} onRightHanlde={this.selectCarDate}></DAtInpute>
                  {!id && <DSelectMap value={carform.registrationCity} bind='registrationCity' require={true} onChangeHandle={_selectMap.bind(this, 'registrationCity')} title='上牌地点' icon='chevron-right' placeholder={!id ? '请选择车辆上牌地点' : ''}></DSelectMap>}
                  {id && <DAtInpute disabled={id} value={carform.registrationCity} bind='registrationCity' require={true} onChange={_bindCarform.bind(this)} title='上牌地点' placeholder={!id ? '请选择车辆上牌地点' : ''}></DAtInpute>}
                  <DAtInpute disabled={id} value={carform.inCondition} bind='inCondition' onChange={_bindCarform.bind(this)} title='进件条件' placeholder={!id ? '请输入进件条件' : ''}></DAtInpute>

                </View>
              }
              <View className='b_carform__form__item'>
                {id && status && <View className='b_carform__form__item__other'>
                  <Text className='b_carform__form_title'>其他信息</Text>

                  <DAtInpute disabled={id} value={carform.entName || '--'} bind='entName' onChange={_bindCarform.bind(this)} title='车商名称' placeholder='请选择车商名称' ></DAtInpute>
                  <DAtInpute disabled={id} value={carform.servicerName || '--'} bind='servicerName' onChange={_bindCarform.bind(this)} title='业务人员' placeholder='请选择业务人员' ></DAtInpute>
                  <DAtInpute disabled={id} value={carform.orgName || '--'} bind='orgName' onChange={_bindCarform.bind(this)} title='中介机构/个人' placeholder='' ></DAtInpute>
                </View>
                }

              </View>
            </AtForm>
          </View>

          <View className='b_carform__footer'>
            {!id && <AtButton className='item_btn' onClick={this.onSubmitHandle.bind(this)}>{this.$router.params.editId ? '重新提交' : '提交'}</AtButton>}
            {/* <DButtonModal text={title} primanyBtn></DButtonModal> */}
          </View>
        </View>}
        {/*推荐*/}
        {id && +current === 1 && <Cardealer carform={carform} />}
        <DSelectColor list={this.state.listColr} count={colorCount} value={selectColor} isOpened={isOpenedColor} onCancelHandle={this.onCancelHandle.bind(this)} onSubmitHandle={this.onSubmitColor.bind(this)}></DSelectColor>
        <View>
          <AtActionSheet className="at-select-one" isOpened={seletOne.isOpened} onClose={seletOne.onClose || seletOne.defNoop}>
            <View className='at-select-one__title'>
              <View className='at-select-one__title_cancel' onClick={seletOne.cancel || seletOne.defNoop}>{seletOne.cancelText || '取消'}</View>
              <View className='at-select-one__title_item'>{seletOne.title}</View>
              <View className='at-select-one__title_submit' onClick={seletOne.commit || seletOne.defNoop}>{seletOne.commitText || '提交'}</View>
            </View>
            <View className='at-select-one__type'>
              {
                seletOne.sList && seletOne.sList.map((item, i) => {
                  return <View onClick={seletOne.selectListItem.bind(this, item)} className={classNames('at-select-one__type_item', item.status ? 'at-select-one__active' : '')} key={i}>{item.text}</View>
                })
              }
            </View>
          </AtActionSheet>
        </View>
        <Ddialog disabledCancel isShow={showAuthTip} content="为了您的交易安全，请进行信息认证 信息认证后可或得更多权限" btnText="前往认证" onCancel={this.onCancel.bind(this)} onSure={this.onSure.bind(this)}></Ddialog>
      </View>
    )
  }
}
